//
//  SystemMsgVC.swift
//  d11
//
//  Created by peale on 2018/7/31.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import MJRefresh
class SystemMsgVC: BXBaseVC,UITableViewDelegate,UITableViewDataSource {
    var requestPath: String?
    var index = 0
    var pageCount = 10
    var dataArray  = [[String: Any]]()
    let  reuseIdentifierID : NSString = "SystemMsgCell"
    var rightItem : UIBarButtonItem?
    var selectDict :[String:IndexPath] = [String:IndexPath]()
    lazy var editingView :UIView = {
        let editingView = UIView.init()
        let deleteBtn  = UIButton.init(type: .custom)
        deleteBtn.setTitle("删除", for: .normal)
        let layerGradient = CAGradientLayer()
        layerGradient.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradient.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 50)
        deleteBtn.layer.addSublayer(layerGradient)
       // deleteBtn.layer.cornerRadius = 5;
       // deleteBtn.layer.masksToBounds = true
        deleteBtn.addTarget(self, action: #selector(self.actionToPopAlert), for: .touchUpInside)
        editingView.addSubview(deleteBtn)
        deleteBtn.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        return editingView
    }()
    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 0, width: self.view.width, height:kScreenHeight-kTabBarBottom), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = UIColor.clear
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never

        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        table.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {
            self.pullToRefresh()
        })
        
        table.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.index = 0
            self.dataArray.removeAll()
            self.selectDict.removeAll()
            self.rightItem?.title = "编辑"
            self.tableView.allowsMultipleSelectionDuringEditing = false
            self.tableView.setEditing(false, animated: true)
            self.showEditingView(isEdit: false)
            self.pullToRefresh()
        })
        
        return table
    }()
    
    //刷新数据
    func pullToRefresh() -> Void {
        self.getRecordList()
    }
    @objc func actionToPopAlert() -> Void{
        if self.selectDict.count == 0 {
             UIHelper.alertSimpleMessage(about: "请选择需要删除的站内信", withDescription: "", in: self)
             return
         }
        let alertsheet = UIAlertController(title: "是否删除?", message: "", preferredStyle: .alert)
               let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (UIAlertAction) in
                   print("选择了取消");

               })
               let  deleteAction = UIAlertAction(title: "确定", style: .default) { (UIAlertAction) in
                   print("选择了确定删除");
                    self.actionToDelete()
               }
               alertsheet.addAction(cancelAction)
               alertsheet.addAction(deleteAction)
               self.present(alertsheet, animated: true) {
                   
                }
    }
    func actionToDelete() ->Void{
 
        var ids = ""
        var signature = ""
        var count = 0
        for(_,value) in self.selectDict{
            count += 1
            let dict =  self.dataArray[value.row]
            ids.append(dict["id"] as? String ?? "")
            if count < self.selectDict.count {
                ids.append(",")
            }
        }
        
        signature = "id"+ids+""+DefaultKey.API_KEY
        self.showLoadHUD(title: "")
        NetWorkRequest(API.bulkDeleteInternalMessage(url: "f4a87db", ids: ids, signature: stringToMD5(string: signature)), completion: { (responseData,statusCode,strData) -> (Void) in
             DispatchQueue.main.async {
                let data = responseData["data"].dictionaryValue
                let response = data["response"]?.dictionaryValue
                 let c = response?["c"]?.int
                 let m = response?["m"]?.stringValue ?? "未知异常"
                 if c == 0{
                  let array = ids.components(separatedBy: ",")
                    for (_,_) in array.enumerated(){
                        for(index,_) in self.dataArray.enumerated(){
                             let dict =  self.dataArray[index]
                             let id = dict["id"] as? String ?? ""
                            if(array.contains(id)){
                                self.dataArray.remove(at: index)
                                break
                            }
                        }
                    }
                    self.selectDict.removeAll()
                    self.tableView.reloadData()
                     UIHelper.alertSimpleMessage(about: "删除成功!", withDescription: "", in: self)
                 }else if c == 21002{
                     UIHelper.displayLoginExpireTip(self)
                 }else{
                     UIHelper.alertSimpleMessage(about: m, withDescription: "", in: self)
                 }
                self.dismissLoadHUD()
            }

        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "删除失败，请稍后重试。", withDescription: "", in: self)
                self._loadView?.removeFromSuperview()
            }
        }
    }
    @objc func editMsg(_ item:UIBarButtonItem) -> Void {
        if item.title == "编辑" {
            if self.dataArray.count == 0 {
                return
            }
            item.title = "取消"
            self.tableView.allowsMultipleSelectionDuringEditing = true
            self.tableView.setEditing(true, animated: true)
            self.showEditingView(isEdit: true)
        }else{
            item.title = "编辑"
            self.tableView.allowsMultipleSelectionDuringEditing = false
            self.tableView.setEditing(false, animated: true)
            self.showEditingView(isEdit: false)
        }
       
    }
    func showEditingView(isEdit:Bool) -> Void{
        self.editingView.snp.updateConstraints{ (make) in
            make.bottom.equalTo(self.view).offset(isEdit == true ? 0 : (50))
        }
         if isEdit == true {
            self.tableView.snp.updateConstraints { (make) in
                make.height.equalTo(kScreenHeight - kNavigationBarHeight - 50)
            }
         }else{
            self.tableView.snp.updateConstraints { (make) in
                make.height.equalTo(kScreenHeight - kNavigationBarHeight - kTabBarBottom)
            }
        }
        
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()

        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
         self.title = "站内信"
         self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.editingView)
        self.tableView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(kScreenHeight - kTabBarBottom - kNavigationBarHeight)
            //make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        self.editingView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset((50))
        }
        self.rightItem = UIBarButtonItem(title: "编辑", style: .plain, target: self, action: #selector(self.editMsg(_:)))
        self.rightItem?.tintColor = UIColor.white
        self.navigationItem.rightBarButtonItem = self.rightItem
        self.dataArray.removeAll()
        self.getRecordList()
        self.showLoadHUD(title: "")
    }
    //html 转成字符串
    func removeHTML(htmlString : String)->String{
        return htmlString.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
    }
    //获取数据
    func getRecordList() -> Void {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let date = Date()
        let datenow = dateFormatter.string(from: date)
        let lastTime: TimeInterval = -(24*60*60*14)
        let lastDate = date.addingTimeInterval(lastTime)
        let dateBefore = dateFormatter.string(from: lastDate)
        let params =  [
            "offset": String(self.index),
            "pageCount": String(self.pageCount),
           "start": dateBefore,
            "end":datenow ,
            ]
        RequestHelper.post(atPath: self.requestPath!, withData: params, withCompletion: { data in
            do{
//                let array2 = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
//                print("记录:\(array2)")
                let array = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
                print("记录:\(array)")
                let numToAdd = array.count
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    self.index += numToAdd
                    self.dataArray.append(contentsOf: array)
                    self.tableView.reloadData()
                    if numToAdd<self.pageCount{
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                    
                        if self.tableView.mj_footer?.isRefreshing == true{
                            self.tableView.mj_footer?.endRefreshing()
                            for(key,value) in self.selectDict{
                                print("获取的值\(value)")
                                
                                self.tableView.selectRow(at: value, animated: true, scrollPosition: UITableView.ScrollPosition.none)
                            }
                        }
                    }
                    if self.tableView.mj_header?.isRefreshing == true
                    {
                        if numToAdd>=self.pageCount{
                            self.tableView.mj_footer?.resetNoMoreData()
                        }
                        self.tableView.mj_header?.endRefreshing()
                    }
                    if self.dataArray.count == 0{
                        MBProgressHUD.showMessage("暂无消息", to: self.view)
                    }
                    
                }
                
            } catch {
                print(String(data: data, encoding: .utf8) as Any)
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    if self.tableView.mj_footer?.isRefreshing == true{
                        self.tableView.mj_footer?.endRefreshing()
                    }
                    if self.tableView.mj_header?.isRefreshing == true
                    {
                        self.tableView.mj_header?.endRefreshing()
                    }
                 
                    UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生异常,\(getErrorString())", in: self)
                }
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                self.tableView.mj_footer?.endRefreshing()
               
                UIHelper.alertSimpleMessage(about: "", withDescription: "取得资料时发生异常", in: self)
            }
        })
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 130
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return  UIView.init()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell :SystemMsgCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? SystemMsgCell
        if cell == nil {
            cell =  SystemMsgCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
        }
        self.removeHTML(htmlString: self.dataArray[indexPath.row]["content"] as! String)
        self.dataArray[indexPath.row]["content"] = self.removeHTML(htmlString: self.dataArray[indexPath.row]["content"] as! String)
        cell?.setData(dict: self.dataArray[indexPath.row])
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (tableView.isEditing) {
            
            self.selectDict[String(indexPath.row)] = indexPath
            return;
        }
        tableView.deselectRow(at: indexPath, animated: false)
        let dict = self.dataArray[indexPath.row]
        PopWindowHelper.showMsgPopView(title: "消息正文", subTitle: dict["content"] as! NSString)
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return UITableViewCell.EditingStyle(rawValue:  UITableViewCell.EditingStyle.delete.rawValue | UITableViewCell.EditingStyle.insert.rawValue) ?? UITableViewCell.EditingStyle.none
    }
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if (tableView.isEditing) {
            self.selectDict[String(indexPath.row)] = nil
            return
        }
    }
}
